<?php
/**
 * Created by PhpStorm.
 * User: lidan
 * Date: 2018/8/28
 * Time: 下午2:30
 */
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use frame\Redis;

require ROOT_PATH . '/vendor/autoload.php';
class App
{
    public static function run() {
        // 启用 slim路由
        $configuration = [
            'settings' => [
                'displayErrorDetails' => true, // 开启错误信息
            ],
        ];
        $c = new \Slim\Container($configuration);
        $app = new \Slim\App($c);
        $app->get('/', function (Request $request, Response $response, array $args) {
            echo 'route err.';
        });

        $app->get('/{platform}/{controller}/{method}', function (Request $request, Response $response, array $args) {
            // 加载平台路由下的配置文件
            self::loadConfigFile(ROOT_PATH . '/app/' . $args['platform']);

            self::loadDbConfig();

//            self::loadRedisConfig();

            // 新建控制器类 调用控制器方法
            $class_name = "{$args['platform']}\\controllers\\{$args['controller']}";
		    $class = new $class_name;
		    $class->{$args['method']}();
	    });
        $app->run();
    }

    public static function loadRedisConfig() {
        Redis::init(C('', true, '__redis'));
    }

    public static function loadDbConfig() {
        $capsule = new Capsule;
        // 创建链接
//        $capsule->addConnection(C('', true, '__database'));
        $capsule->addConnection(C('database'));
        // 设置全局静态可访问
        $capsule->setAsGlobal();
        // 启动Eloquent
        $capsule->bootEloquent();
    }


    public static function loadConfigFile($path) {
        if(!is_dir($path)) return ;
        $dh = opendir($path);
        if($dh == false) return ;
        while (($file = readdir($dh)) != false) {
            if($file != '.' && $file != '..') {
                $file_path = $path . '/' . $file;
                if(is_file($file_path)) {
                    $file_content = require $file_path;
                    if(is_array($file_content)) { // 加载配置文件
                        $config_key = '__' . str_replace('.php', '', $file);
                        $GLOBALS[$config_key] = $file_content;
                    }
                }
            }
        }
        closedir($dh);
    }



}